package com.example.sakurasay.passwordbook.ui

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.sakurasay.databinding.ItemIndependentPasswordBinding
import com.example.sakurasay.passwordbook.data.entities.IndependentPasswordEntry

class IndependentPasswordAdapter :
    ListAdapter<IndependentPasswordEntry, IndependentPasswordAdapter.PasswordViewHolder>(PasswordDiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PasswordViewHolder {
        val binding =
            ItemIndependentPasswordBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return PasswordViewHolder(binding)
    }

    override fun onBindViewHolder(holder: PasswordViewHolder, position: Int) {
        val currentItem = getItem(position)
        holder.bind(currentItem)
    }

    class PasswordViewHolder(private val binding: ItemIndependentPasswordBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(entry: IndependentPasswordEntry) {
            binding.apply {
                textViewAccountName.text = entry.accountName
                textViewUsername.text = entry.username
            }
        }
    }

    class PasswordDiffCallback : DiffUtil.ItemCallback<IndependentPasswordEntry>() {
        override fun areItemsTheSame(oldItem: IndependentPasswordEntry, newItem: IndependentPasswordEntry) =
            oldItem.id == newItem.id

        override fun areContentsTheSame(oldItem: IndependentPasswordEntry, newItem: IndependentPasswordEntry) =
            oldItem == newItem
    }
}